<template>
  <el-dialog
    v-model="visible"
    :title="groupData.shopGroupId ? '修改分组' : '新建分组'"
    width="900px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @closed="closed"
  >
    <div class="commodityBox">
      <div class="newGroupBox">
        <el-form
          ref="formRef"
          class="formBox"
          :model="groupData"
          label-width="80px"
          :rules="groupBuyRules"
        >
          <el-form-item label="分组名称" prop="groupName">
            <el-input
              v-model="groupData.groupName"
              maxlength="20"
              placeholder="请输入分组名称"
              onblur="value=value.replace(/(^\s*)|(\s*$)/g, '')"
            />
          </el-form-item>
          <el-form-item label="分组描述">
            <el-input
              v-model="groupData.groupDescribe"
              maxlength="200"
              type="textarea"
              :rows="4"
              placeholder="请输入分组描述"
            />
          </el-form-item>
          <el-form-item label="分组商品" prop="addType">
            <div class="btnBox">
              <el-radio v-model="groupData.addType" label="1" /><span
                @click="manualAdd"
              >手动添加</span>
              <el-radio v-model="groupData.addType" label="2" />
              <span @click="intelligentAdd">智能添加</span>
            </div>
          </el-form-item>
        </el-form>
        <el-divider />
        <div
          v-if="groupData.conditions.length > 0 && groupData.addType === '2'"
          class="intelDataBox"
        >
          <div class="intelTit">智能添加已选条件</div>
          <div class="intelList">
            <div
              v-for="(item, index) of groupData.conditions"
              :key="index"
              class="intelItem"
            >
              <div class="itemBox">
                <span v-if="item.type === 1">库存</span>
                <span v-if="item.type === 2">价格</span>
                <span v-if="item.type === 3">重量</span>
                <span v-if="item.type === 4">销量</span>
                <span v-if="item.calculation === 1">大于</span>
                <span v-if="item.calculation === 2">等于</span>
                <span v-if="item.calculation === 3">小于</span>
                <span>{{ item.number }}</span>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="groupData.addType === '1'"
          class="isSelectList"
        >
          <h3 class="isSelectTit">已选商品</h3>
          <div class="tableBox">
            <el-table
              :data="products"
              border
              :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
              tooltip-effect="dark"
              style="width: 100%"
              max-height="400"
            >
              <el-table-column label="产品主图" width="220" align="center">
                <template #default="scope">
                  <img
                    height="80"
                    width="80"
                    :src="scope.row.image"
                    alt
                    srcset
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="productName"
                label="产品名称"
                width="220"
                align="center"
              />
              <el-table-column
                prop="originalPrice"
                label="价格（元）"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                prop="stockNumber"
                label="库存（件）"
                align="center"
                show-overflow-tooltip
              />
            </el-table>
<!--            <el-pagination-->
<!--              :current-page="productsPage"-->
<!--              :page-sizes="[5, 10, 20, 50, 100]"-->
<!--              :page-size="productsPageSize"-->
<!--              layout="total, sizes, prev, pager, next, jumper"-->
<!--              :total="products.length"-->
<!--              style="margin: 30px 0 0 0;"-->
<!--              @size-change="handleSizeChange"-->
<!--              @current-change="handleCurrentChange"-->
<!--            />-->
          </div>
        </div>
      </div>
    </div>
    <!-- 手动添加弹框 -->
    <el-dialog
      v-model="isShowManualAdd"
      title="手动添加商品"
      width="65%"
      top="50px"
      center
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <!-- 搜索 -->
      <div class="formSearch">
        <el-form :inline="true" :model="formInline">
          <el-form-item label="商品名称">
            <el-input
              v-model="formInline.search"
              maxlength="20"
              placeholder="搜索商品名称或商品ID"
            />
          </el-form-item>
          <el-form-item class="tagCustomer" label="库存数量">
            <el-input v-model="formInline.minStock" maxlength="9" /><span>至</span><el-input v-model="formInline.maxStock" maxlength="9" />
          </el-form-item>
          <el-form-item class="tagCustomer" label="价格">
            <el-input v-model="formInline.minPrice" maxlength="9" /><span>至</span><el-input v-model="formInline.maxPrice" maxlength="9" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="search">查询</el-button>
            <el-button plain @click="clearData">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tableBox">
        <el-table
          :data="shopListData"
          ref="multipleTableRef"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          :row-key="row=>row.productId"
          max-height="550"
          @select="handleSelect"
          @select-all="handleSelectAll"
        >
          <el-table-column
              type="selection"
              :reserve-selection="true"
              width="55"
          />
          <el-table-column label="产品主图" width="220" align="center">
            <template #default="scope">
              <img height="80" width="80" :src="scope.row.image" alt srcset />
            </template>
          </el-table-column>
          <el-table-column
            prop="productName"
            label="产品名称"
            width="220"
            align="center"
          />
          <el-table-column
            prop="originalPrice"
            label="价格（元）"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="stockNumber"
            label="库存（件）"
            align="center"
            show-overflow-tooltip
          />
        </el-table>
        <el-pagination
          :current-page="formInline.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="formInline.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="shopTotal"
          style="margin: 30px 0 0 0;"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <template #footer>
        <el-button type="primary" @click="saveIdList">确 定</el-button>
        <el-button @click="closeSelect">取 消</el-button>
      </template>
    </el-dialog>
    <!-- 智能添加弹框 -->
    <el-dialog
      v-model="isIntelligentAdd"
      title="智能添加商品"
      width="50%"
      top="50px"
      class="group-dialog"
      center
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <div class="znAddBox">
        <div class="conditionBox">
          <span class="anAddTit">满足条件</span>
          <el-radio v-model="condition" label="1">全部满足</el-radio>
          <el-radio v-model="condition" label="2">任意满足</el-radio>
        </div>
        <div class="screenBox">
          <span class="anAddTit">筛选条件</span>
          <div class="crowdOptions">
            <div
              v-for="(item, index) of selectConditions"
              :key="item.type"
              class="condition"
            >
              <div class="flexBox">
                <div class="rightInfo">
                  <el-select
                    v-model="item.type"
                    placeholder="请选择"
                    style="width: 120px"
                    @change="changeType(item, index)"
                  >
                    <el-option
                      v-for="typeItem in options"
                      v-show="!types.includes(typeItem.type)"
                      :key="typeItem.type"
                      :label="typeItem.name"
                      :value="typeItem.type"
                    />
                  </el-select>
                </div>
                <div class="purchase">
                  <el-select v-model="item.calculation" placeholder="请选择" style="width: 120px">
                    <el-option
                      v-for="calculationItem in calculationList"
                      :key="calculationItem.value"
                      :label="calculationItem.label"
                      :value="calculationItem.value"
                    />
                  </el-select>
                </div>
                <div class="valueBox">
                  <el-input v-model="item.number" maxlength="9" />
                </div>
                <div
                  v-if="selectConditions.length !== 1"
                  class="deleteIcon"
                  @click="deleteOptions(item, index)"
                >
                  <el-icon size="20" color="red"><RemoveFilled /></el-icon>
                </div>
              </div>
            </div>
            <div
              v-if="groupData.conditions.length !== 4"
              class="addCondition"
              @click="addCondition"
            >
              <el-icon size="20"><CirclePlusFilled /></el-icon>
              <span>添加筛选条件</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="saveOptions">确 定</el-button>
        <el-button @click="closeOptions">取 消</el-button>
      </template>
    </el-dialog>
    <template #footer>
      <div class="submitBox">
        <el-button type="primary" :loading="btnLoading" @click="addGroup(formRef)">提 交</el-button>
        <el-button @click="closed">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick } from 'vue'
function GroupData () {
  this.condition = null // 满足条件 1-全部满足 2-任意满足
  this.conditions = [
    // 筛选条件数组
    // {
    //   calculation: 1, // 运算符 1-大于 2-等于 3-小于
    //   ids: [], // 已满足部分条件的商品id数组
    //   number: null, // 数值
    //   type: 1 // 类型 1-库存 2-价格 3-重量 4-销量
    // }
  ]
  this.groupDescribe = '' // 分组描述
  this.groupImage = '' // 分组封面图片地址
  this.groupName = '' // 分组名称
  this.ids = [] // 商品id数组
  this.shopGroupId = null // 商品分组id
  this.addType = '1' // 1手动添加 2智能添加
}
import {
  commodityListAdd,
  commodityListUpdate,
  getGroupList,
  commodityListGetById,
} from '@/api/commodity'

const formRef = ref(null)
const formInline = ref({
  maxPrice: null, // 价格最大值
  maxStock: null, // 库存数量最大值
  minPrice: null, // 价格最小值
  minStock: null, // 库存数量最小值
  page: 1, // 当前页
  pageSize: 10, // 每页记录数
  search: '' // 搜索字段
})
const visible = ref(false)
const btnLoading = ref(false)
const groupData = ref(new GroupData())
const isShowManualAdd = ref(false) // 手动添加弹窗
const isIntelligentAdd = ref(false) // 自动添加弹窗
const shopListData = ref([])
const selectShopList = ref([])
const shopTotal = ref(1)
const tableData = ref([])
const multipleSelection = ref([])
const multipleTableRef = ref()
// 智能添加
const condition = ref('1')
const types = ref([1])
const options = ref([
  {
    type: 1,
    name: '库存'
  },
  {
    type: 2,
    name: '价格'
  },
  {
    type: 3,
    name: '重量'
  },
  {
    type: 4,
    name: '销量'
  }
])
const calculationList = ref([
  {
    label: '大于',
    value: 1
  },
  {
    label: '等于',
    value: 2
  },
  {
    label: '小于',
    value: 3
  }
])
const checkAddType = (rule, value, callback) => {
  if (value === '1' && groupData.value.ids.length === 0) {
    return callback(new Error('请手动添加分组商品'))
  } else if (value === '2' && groupData.value.conditions.length === 0) {
    return callback(new Error('请添加智能筛选条件'))
  } else {
    callback()
  }
}
const groupBuyRules = ref({
  groupName: [
    { required: true, message: '请输入分组名称', trigger: 'blur' }
  ],
  // addType: [
  //   { required: true, validator: checkAddType, trigger: 'change' }
  // ]
})
const products = ref([]) // 确定已选商品
const productsPage = ref(1)
const productsPageSize = ref(5)
const selectConditions = ref([]) // 当前选择筛选条件
// 已选智能筛选条件
const intelData = ref([])
const emits = defineEmits(['reload'])

// 打开分组弹窗
const open = (id) => {
  if (id) {
    groupData.value.shopGroupId = id
    getDetailFn()
  }
  visible.value = true
}
defineExpose({ open })

// 分组弹窗关闭后清空表单数据
const closed = () => {
  formRef.value.resetFields()
  groupData.value = new GroupData()
  products.value = []
  multipleTableRef.value?.clearSelection()
  multipleSelection.value = []
  shopListData.value = []
  selectShopList.value = []
  visible.value = false
}

// 初始化查询所有数据
const getAll = async () => {
  const res = await getGroupList(formInline.value)
  shopTotal.value = res.data.total
  shopListData.value = res.data.list
  nextTick(() => {
    for (let i = 0; i < shopListData.value.length; i++) {
      if (groupData.value.ids.includes(shopListData.value[i].productId)) {
        const row = shopListData.value[i];
        multipleTableRef.value.toggleRowSelection(row, true);
      }
    }
  })
}
// 获取详情
const getDetailFn = () => {
  commodityListGetById({ shopGroupId: groupData.value.shopGroupId }).then(
    (res) => {
      if (res.code === '') {
        groupData.value.groupDescribe = res.data.groupDescribe
        groupData.value.groupName = res.data.groupName
        multipleSelection.value = res.data.products
        products.value = [...res.data.products]
        selectShopList.value = [...res.data.products]
        const shopList = []
        products.value.forEach((i) => {
          shopList.push(i.productId)
        })
        groupData.value.ids = shopList
        groupData.value.shopGroupId = res.data.shopGroupId
      } else {
        ElMessage({
          message: res.message,
          type: 'error',
        })
      }
    }
  )
}
const manualAdd = () => {
  groupData.value.addType = '1'
  // this.groupData.conditions = []
  // this.groupData.condition = null
  isShowManualAdd.value = true
  getAll()
}
// 商品表格多选
// const handleSelectionChange = (val) => {
//   multipleSelection.value = val
//   console.log(multipleSelection.value, 'test')
//   groupData.value.ids = []
// }
// 分页大小
const handleSizeChange = (val) => {
  formInline.value.pageSize = val
  getAll()
}
// 分页
const handleCurrentChange = (val) => {
  formInline.value.page = val
  getAll()
}


const handleSelect = (e, row) => {
  if (selectShopList.value.findIndex(item => item.productId === row.productId) >= 0) {
    // 删除
    selectShopList.value.splice(selectShopList.value.findIndex(item => item.productId === row.productId), 1);
  } else {
    // 新增
    selectShopList.value.push(row)
  }
  console.log(selectShopList.value, 'ids')
}
const handleSelectAll = (e) => {
  if (e.length > 0) {
    e.forEach(item => {
      if (!selectShopList.value.includes(item.productId)) {
        selectShopList.value.push(item)
      }
    });
  } else {
    // 当前页全部删除
    shopListData.value.forEach((row) => {
      const index = selectShopList.value.findIndex(item => item.productId === row.productId);
      selectShopList.value.splice(index, 1);
    });
  }
}
const intelligentAdd = () => {
  groupData.value.addType = '2'
  if (selectConditions.value.length === 0) {
    selectConditions.value.push({
      calculation: 1, // 运算符 1-大于 2-等于 3-小于
      ids: [], // 已满足部分条件的商品id数组
      number: null, // 数值
      type: 1, // 类型 1-库存 2-价格 3-重量 4-销量
    })
  }
  groupData.value.condition = 1
  isIntelligentAdd.value = true
}
// 保存手动选择商品
const saveIdList = () => {
  // if (multipleSelection.value.length === 0) {
  //   groupData.value.ids = []
  // }
  const shopList = []
  selectShopList.value.forEach((i) => {
    shopList.push(i.productId)
  })
  groupData.value.ids = shopList
  products.value = selectShopList.value
  isShowManualAdd.value = false
}
// 取消手动选择商品
const closeSelect = () => {
  isShowManualAdd.value = false
}
// 更改当前选项
const changeType = (item, index) => {
  let crowdData = groupData.value.conditions
  types.value = []
  crowdData.forEach((i) => {
    types.value.push(i.type)
  })
  if (item.type === 9 || item.type === 10) {
    groupData.value.conditions[index].calculation = 1
  }
}
// 删除当前筛选
const deleteOptions = (item, index) => {
  types.value.splice(index, 1)
  selectConditions.value.splice(index, 1)
}
// 保存智能匹配配置
const saveOptions = () => {
  let groupCond = selectConditions.value
  let optionArr = options.value
  for (let i = 0; i < groupCond.length; i++) {
    if (groupCond[i].number === null || groupCond[i].number === '') {
      for (let j = 0; j < optionArr.length; j++) {
        if (groupCond[i].type === optionArr[j].type) {
          ElMessage({
            message: `选项为${optionArr[j].name}的内容不能为空!`,
            type: 'warning',
          })
          return false
        }
      }
    }
  }
  groupData.value.conditions = deepClone(selectConditions.value)
  isIntelligentAdd.value = false
}
// 保存提交
const addGroup = (formEl) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      btnLoading.value = true
      if (groupData.value.addType === '1') {
        groupData.value.conditions = []
        groupData.value.condition = null
      } else {
        groupData.value.ids = []
        products.value = []
        multipleSelection.value = []
      }
      if (groupData.value.shopGroupId) {
        // 修改分组
        commodityListUpdate(groupData.value).then((res) => {
          if (res.code === '') {
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
            closed()
            emits('reload')
          } else {
            ElMessage({
              message: res.message,
              type: 'error',
            })
          }
        }).finally(() => {
          btnLoading.value = false
        })
      } else {
        // 新增分组
        commodityListAdd(groupData.value).then((res) => {
          if (res.code === '') {
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
            visible.value = false
            emits('reload')
          } else {
            ElMessage({
              message: res.message,
              type: 'error',
            })
          }
        }).finally(() => {
          btnLoading.value = false
        })
      }
    } else {
      return false
    }
  })
}
// 取消智能匹配配置
const closeOptions = () => {
  isIntelligentAdd.value = false
  selectConditions.value = []
}
// 添加筛选
const addCondition = () => {
  for (let i = 1; i <= options.value.length; i++) {
    if (!types.value.includes(i)) {
      selectConditions.value.push({
        calculation: 1, // 运算符 1-大于 2-等于 3-小于
        ids: [], // 已满足部分条件的商品id数组
        number: null, // 数值
        type: i, // 类型 1-库存 2-价格 3-重量 4-销量
      })
      types.value.push(i)
      break
    }
  }
}
// 手动查询商品
const search = () => {
  getAll()
}
const clearData = () => {
  formInline.value = {
    maxPrice: null, // 价格最大值
    maxStock: null, // 库存数量最大值
    minPrice: null, // 价格最小值
    minStock: null, // 库存数量最小值
    page: 1, // 当前页
    pageSize: 10, // 每页记录数
    search: '', // 搜索字段
  }
  getAll()
}
const deepClone = (obj) => {
  let objClone = JSON.parse(JSON.stringify(obj))
  return objClone
}
</script>

<style lang="scss" scoped>
.commodityBox {
  background: #ffffff;
  .groupTit {
    font-size: 22px;
    color: #333333;
    font-weight: 500;
  }
  .newGroupBox {
    width: 800px;
    margin: 20px;
    .btnBox {
      display: flex;
      align-items: center;
      margin-left: 10px;
      span {
        display: block;
        width: 80px;
        height: 35px;
        line-height: 35px;
        background: #3A68F2;
        color: #ffffff;
        font-size: 12px;
        text-align: center;
        border-radius: 4px;
        margin-right: 20px;
        cursor: pointer;
        position: relative;
      }
      i {
        display: block;
        font-style: normal;
        font-size: 12px;
        color: #3A68F2;
        width: 30px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        border: 1px solid #3A68F2;
        border-radius: 50%;
        position: absolute;
        right: -10px;
        top: -10px;
        z-index: 999;
        background: #ffffff;
      }
    }
  }
}
.submitBox {
  width: 100%;
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
.isSelectList {
  h3 {
    font-size: 14px;
    color: #666666;
    font-weight: bold;
    margin-bottom: 20px;
  }
}
.el-form {
  .el-form-item {
    :deep(.el-form-item__label) {
      font-weight: bold;
    }
  }
}
.znAddBox {
  padding: 30px 30px 0 30px;
  .screenBox {
    display: flex;
    margin-top: 30px;
    .crowdOptions {
      margin-left: 20px;
    }
  }
  .condition {
    margin-bottom: 20px;
    p {
      font-size: 14px;
      color: #666666;
      margin-left: 100px;
    }
    .flexBox {
      display: flex;
      align-items: center;
      .leftTit {
        width: 100px;
        text-align: right;
        font-size: 14px;
        color: #606260;
        font-weight: 700;
        padding-right: 12px;
      }
      .purchase {
        margin-left: 30px;
      }
      .tagList {
        margin-left: 30px;
      }
      .valueBox {
        display: flex;
        align-items: center;
        margin-left: 30px;
      }
      .deleteIcon {
        margin-left: 30px;
        .el-icon-remove:before {
          color: #ff5c5c;
          font-size: 22px;
          cursor: pointer;
        }
      }
    }
  }
}
.addCondition {
  margin: 50px 0 0 0;
  display: flex;
  align-items: center;
  cursor: pointer;
  width: 160px;
  .el-icon-circle-plus:before {
    font-size: 24px;
    color: #999999;
  }
  span {
    margin-left: 10px;
  }
}
.intelDataBox {
  width: 200px;
  // margin: 60px 0 0 150px;
  .intelTit {
    font-size: 14px;
    color: #666666;
    font-weight: 500;
  }
  .intelList {
    margin-top: 20px;
    border: 1px solid #eeeeee;
    .intelItem {
      display: flex;
      align-items: center;
      background: #fdfdfd;
      height: 35px;
      line-height: 35px;
      border-bottom: 1px solid #eeeeee;
      padding-left: 20px;
      span {
        font-size: 13px;
        color: #666666;
        font-weight: 600;
      }
    }
  }
}
</style>

<style scoped>
.newGroupBox :deep(.formBox) {
  width: 500px;
}
.znAddBox :deep(.conditionBox) {
  display: flex;
  align-items: center;
}
.znAddBox :deep(.conditionBox) .anAddTit {
  margin-right: 20px;
}
.tagCustomer :deep(.el-form-item__content) {
  display: flex;
  width: 260px;
}
.tagCustomer {
  display: flex !important;
}
.tagCustomer :deep(.el-form-item__content) span {
  margin: 0 5px;
}
.formSearch :deep(.el-form) {
  display: flex;
  flex-wrap: wrap;
}
.btnBox :deep(.el-radio) {
  margin-right: 8px;
}
.btnBox :deep(.el-radio__label) {
  display: none;
}
</style>
